// const cloud = require('wx-server-sdk');

// cloud.init({
//   env: cloud.DYNAMIC_CURRENT_ENV
// });
'use strict';
const cloudbase = require("@cloudbase/node-sdk");
const app = cloudbase.init({
    env: cloudbase.SYMBOL_CURRENT_ENV
});
const db = cloud.database();
const _ = db.command;

exports.main = async (event, context) => {
  var _pageSize = 10;
  var _pageNum = 1;
  var query = {}
  if (event.pageNum != undefined && event.pageNum != null) {
    _pageNum = event.pageNum
  }
  if (event.pageSize != undefined && event.pageSize != null) {
    _pageSize = event.pageSize
  }
  if (event.searchCode != undefined && event.searchCode != null && event.searchCode != '') {
    query.name = new db.RegExp({
      regexp: searchCode
    })
  }

  return new Promise((resolve, reject) => {
    db.collection('drop_point').aggregate().match(query)
    .lookup({
      from: 'device',
      localField: '_id',
      foreignField: 'drop_point._id',
      as: 'devices'
    })
    .skip((_pageNum - 1) * _pageSize).limit(_pageSize).end()
      .then(res => {
        var data = res.data
        db.collection('drop_point').where(query).count()
          .then(res => {
            var result = {
              data: data,
              total: res.total
            }
            resolve(result)
          }).catch(err => {
            reject(err)
          })
      }).catch(err => {
        reject(err)
      })
  })
}